<template>
  <el-drawer
    ref="drawer"
    size="56%"
    title="选择习题"
    :visible.sync="visible"
    direction="rtl"
    custom-class="demo-drawer"
    :before-close="cancel"
    destroy-on-close
  >
    <el-form ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item label="题目" prop="content">
        <el-input
          v-model="queryParams.content"
          placeholder="请输入"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="科目" prop="subject">
        <el-select v-model="queryParams.subject" filterable placeholder="请选择科目">
          <el-option
            v-for="(item, index) in subjectList"
            :key="index"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="题目类型" prop="subject_type">
        <el-select v-model="queryParams.subject_type" placeholder="请选择类型" size="small">
          <el-option v-for="(item,index) in topicType" :key="index" :label="item" :value="index" />
        </el-select>
      </el-form-item>
      <el-form-item style="float:right">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table
      ref="multipleTable"
      v-loading="loading"
      :data="dataList"
      height="400"
      @select="handleSelection"
      @select-all="handleSelectionAll"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" header-align="center" width="50" label="序号" align="center" />
      <el-table-column header-align="center" prop="subject_type" label="题型" align="center">
        <template slot-scope="scope">
          <span>{{ topicType[scope.row.subject_type] }}</span>
        </template>
      </el-table-column>
      <el-table-column header-align="center" prop="subject" label="科目" align="center" />
      <el-table-column
        header-align="center"
        prop="content"
        label="题目"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <el-image v-if="urlTest.test(scope.row.content)" :src="scope.row.content" />
          <span v-else>{{ scope.row.content }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdAt" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt) }}</span>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageIndex"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <div style="position: fixed;bottom: 10px;right: 30px">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-drawer>
</template>
<script>
import { getQuestionList } from '@/api/admin/sys-question'
import { getConfigKey, getSubject } from '@/api/admin/sys-course'
export default {
  name: 'Exercises',
  props: {
    visible: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    subjectType: {
      type: String,
      default: () => {
        return undefined
      }
    },
    idList: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
        content: undefined,
        subject_type: undefined
      },
      loading: false,
      dataList: [],
      ids: [],
      total: 0,
      flagchange: 0,
      topicType: {},
      urlTest: /^http(s|):\/\/\S*?\//,
      subjectList: []
    }
  },
  watch: {
    visible: {
      handler(val) {
        if (val === true) {
          this.flagchange++
        }
        if (this.flagchange === 1 && this.visible === true) {
          getConfigKey().then(response => {
            this.topicType = JSON.parse(response?.data?.configValue)
          })
        }
        if (
          this.flagchange === 1 &&
          this.visible === true &&
          !this.subjectType
        ) {
          this.getList()
        }
      }
    },
    subjectType: {
      handler(newVal) {
        this.queryParams = {
          ...this.queryParams,
          subject_type: this.subjectType
        }
        this.getList()
      }
    },
    idList: {
      handler(newVal) {
        this.ids = newVal
      }
    }
  },
  created() {
    getSubject().then(res => {
      this.subjectList = res?.data || []
    })
  },
  methods: {
    getList() {
      this.loading = true
      try {
        getQuestionList(this.queryParams)
          .then(response => {
            this.dataList = response.data.list
            this.total = response.data.count
            this.$nextTick(() => {
              response.data?.list?.forEach(row => {
                this.ids?.forEach(id => {
                  if (row.id === id) {
                    this.$refs.multipleTable.toggleRowSelection(row)
                  }
                })
              })
            })
          })
          .finally(() => {
            this.loading = false
          })
      } catch (error) {
        console.log(error)
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageIndex = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleSelectionAll(all) {
      const idList = all.map(item => {
        return item.id
      })
      this.$nextTick(() => {
        this.ids = Array.from(new Set([...idList, ...this.ids]))
      })
    },
    // 选中数据
    handleSelection(selection, row) {
      const selectId = row.id
      if (this.ids.indexOf(selectId) === -1) {
        this.ids.push(selectId)
      } else {
        this.ids = this.ids.filter(item => item !== selectId)
      }
    },
    submitForm() {
      if (this.ids.length < 1) {
        return this.msgError('选择习题')
      }
      this.$emit('submitForm', this.ids.join())
    },
    cancel() {
      this.$emit('cancel')
    }
  }
}
</script>
